package com.ctl.juc;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * 线程1执行结束后给线程2传参然后线程2在执行
 */
public class CompletableFutureTest2 implements Runnable {
    static Logger logger = LoggerFactory.getLogger(CompletableFutureTest2.class);

    private CompletableFuture<String> re = null;

    public CompletableFutureTest2(CompletableFuture<String> re) {
        this.re = re;
    }

    public void run() {
        logger.info("{} start run",Thread.currentThread().getName()+"-"+Thread.currentThread().getId());
        String myRe = "";
        try {
            myRe = re.get();
        } catch (Exception e) {
            logger.error("", e);
        }
        logger.info("msg from other thread {}", myRe);
        logger.info("{} end run",Thread.currentThread().getName()+"-"+Thread.currentThread().getId());

    }

    public static void main(String[] args) throws InterruptedException {
        final CompletableFuture<String> future = new CompletableFuture<>();
        new Thread(new CompletableFutureTest2(future)).start();
        logger.info("start");
        //模拟长时间的计算过程
        Thread.sleep(1000);
        logger.info("sleep over");
        new Thread(() -> {
            logger.info("thread={} start", Thread.currentThread().getName()+"-"+Thread.currentThread().getId());
            try {
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                logger.error("", e);
            }
            logger.info("thread={} start notify AskThread ", Thread.currentThread().getName()+"-"+Thread.currentThread().getId());
            future.complete(Thread.currentThread().getName()+"-"+Thread.currentThread().getId()+" is over");
            logger.info("thread={} over notify AskThread ", Thread.currentThread().getName()+"-"+Thread.currentThread().getId());
        }).start();
        //告知完成结果
        logger.info("{}","main is over");
    }
}